<template>
  <Modal
    width="700"
    v-model="visiable"
    :closable="false"
    :mask-closable="false"
    :title="modalTitle"
  >
    <Form ref="formValidate" :model="formFields" :rules="ruleValidate" :label-width="80" class="roleForm">
      <Row>
        <Col :span="span">
          <FormItem label="角色姓名" prop="roleName">
            <Input v-model="formFields.roleName" />
          </FormItem>
        </Col>
        <Col :span="span">
          <FormItem label="备注" prop="description">
            <Input v-model="formFields.description" />
          </FormItem>
        </Col>
        <Col :span="span">
          <FormItem label="权限配置" prop="menuCodes" :show-message="false">
            <Tree
              ref="modal"
              :data="authorityList"
              v-model="formFields.menuCodes"
              show-checkbox
              @on-check-change="handleSelected"
            />
            <div class="errorMessage">{{errorMessage}}</div>
          </FormItem>
        </Col>
      </Row>
    </Form>
    <div slot="footer">
      <Button @click="handleCancel">取消</Button>
      <Button type="primary" @click="handleOk" :loading="isLoading">确定</Button>
    </div>
</Modal>
</template>

<script>
import {
  queryAuthyTree,
  addRole,
  queryRoleInfo,
  editRole
} from '@/api/role-manage.js'
import { addProp } from '@/libs/util.js'

export default {
  name: 'AddRoleModal',
  props: ['modalTitle'],
  data: function () {
    return {
      span: 12, // 设置col的span
      isLoading: false,
      isEdit: 'add',
      visiable: false,
      treeData: [], // 暂存tree数据
      authorityList: [],
      selectedCodes: [],
      formFields: {
        roleName: '',
        description: '',
        menuCodes: []
      },
      ruleValidate: {
        roleName: [{ required: true, message: '请填写角色名称', trigger: 'blur' }],
        menuCodes: [{ type: 'array', required: true }]
      },
      errorMessage: ''
    }
  },
  methods: {
    isShowModal (type, row) {
      this.visiable = true
      this.isEdit = type
      if (row.roleCode) {
        this.getEditInfo(this.treeData, row.roleCode)
      }
      if (type === 'add') {
        this.authorityList = addProp(this.treeData)
      }
    },
    handleSelected (selectedValues) {
      const authorityCodes = selectedValues.map(item => item.id)
      this.formFields.menuCodes = authorityCodes
      this.validateAuthority()
    },
    validateAuthority () {
      const authorityCodes = this.formFields.menuCodes
      if (authorityCodes.length < 1) {
        this.errorMessage = '请选择权限'
        return true
      } else {
        this.errorMessage = ''
        return false
      }
    },
    handleOk () {
      this.validateAuthority()
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          let messageText = '添加成功'
          let disptch = addRole
          if (this.isEdit === 'edit') {
            messageText = '修改成功'
            disptch = editRole
          }
          this.isLoading = true
          disptch(this.formFields).then((response) => {
            const { data } = response
            if (data.code === 2000) {
              this.$emit('handleSubmit')
              this.visiable = false
              this.$Message.success(messageText)
            } else {
              this.$Message.error(data.msg || '系统错误，请稍后再试')
            }
            this.isLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.$refs['formValidate'].resetFields() // 重置form表单
      this.errorMessage = ''
      this.visiable = false
      // this.$emit('closeModal')
    },
    getTreeData (checkedCodes = []) {
      queryAuthyTree().then((response) => {
        const { data } = response
        if (data.code === 2000) {
          this.treeData = data.data
        } else {
          this.$Message.error(data.msg || '系统错误，请稍后再试')
        }
        this.loading = false
      })
    },
    getEditInfo (treeData, roleCode) {
      queryRoleInfo(roleCode).then((response) => {
        const { data } = response
        if (data.code === 2000) {
          const { roleName, description, menuCodes } = data.data
          this.authorityList = addProp(treeData, menuCodes)
          this.formFields = {
            roleName,
            description,
            menuCodes,
            roleCode
          }
        } else {
          this.$Message.error(data.msg)
        }
      })
    }
  },
  mounted () {
    this.getTreeData()
  }
}
</script>
<style lang="less">
  .errorMessage {
    color: #ed4014;
    line-height: 0
  }
  .roleForm {
    max-height: 500px;
    overflow-y: auto;
  }
</style>
